<?php

namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\TaskService;

/**
 * 日常任务
 */
class TaskLogic extends BackendLogic
{
    public function __construct()
    {
        $this->service =Container::get(TaskService::class);
    }
    /**
     * 添加编辑任务
     * @return array
     */
    public  function edit()
    {
        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (empty($data['code'])) throw  new  ApiException('请选择编码');
        if (empty($data['title'])) throw  new  ApiException('请输入名称');
        if (empty($data['icon'])) throw  new  ApiException('请上传图标');
        if (empty($data['type'])) throw  new  ApiException('请选择任务类型');
        if ($data['type'] != 1 && empty($data['total_progress'])) throw  new  ApiException('请输入任务次数');
        if (empty($data['reward_type'])) throw  new  ApiException('请选择奖励类型');
        if ($data['reward_type'] == 1 && empty($data['reward'])) throw  new  ApiException('请输入奖励值');
        if ($data['reward_type'] == 2 && empty($data['reward1'])) throw  new  ApiException('请输入奖励值');
        if ($data['reward_type'] == 2 && empty($data['reward2'])) throw  new  ApiException('请输入奖励值');
        if (empty($data['button_text'])) throw  new  ApiException('请输入按钮文字');
        if (empty($data['desc'])) throw  new  ApiException('请输入描述');
        if (empty($data['sort'])) throw  new  ApiException('请输入排序');
        $save['code'] = $data['code'];
        $save['title'] = $data['title'];
        $save['icon'] = $data['icon'];
        $save['type'] = $data['type'];
        $save['reward_type'] = $data['reward_type'];
        if ($data['reward_type'] == 1) {
            $save['reward'] = $data['reward'];
        } else {
            $reward[] = $data['reward1'];
            $reward[] = $data['reward2'];
            $save['reward'] = implode('-', $reward);
        }
        if ($data['type'] != 1) {
            $save['total_progress'] = $data['total_progress'];
        } else {
            $save['total_progress'] = 1;
        }
        $save['desc'] = $data['desc'];
        $save['sort'] = $data['sort'];
        $save['button_text'] = $data['button_text'];

        if ($id == 0) {
            $this->service->add($save);
        } else {
            $this->service->save($save, $id);
        }
        return message();

    }

    /**
     * 任务唯一code
     * @return array
     */
    public  function getTaskUnique(): array
    {
        $data = $this->service->getTaskUnique();
        return message($data);
    }

}